package com.sise.bl.controller;

import com.sise.bl.entity.User;
import com.sise.bl.service.UserService;
import com.sise.bl.utils.Base64Utils;
import com.sise.bl.utils.Constants;
import com.sise.bl.utils.MD5Utils;
import com.sise.bl.utils.RandomUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
@SessionAttributes({"loginUser", "code"})
public class UserController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam Map<String, String[]> parameterMap, Model model) {
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //2.完善用户信息
        //已经赋值： 用户名 密码 邮箱 性别
        //没有赋值： 激活状态 账号类型 激活码
        user.setUstatus(Integer.valueOf(Constants.USER_NOT_ACTIVE)); //未激活状态 0 激活 1
        user.setUrole(Constants.ROLE_CUSTOMER); //普通客户0  管理员1
        user.setCode(RandomUtils.createActive());

        //需要处理的属性：密码 md5进行加密处理
        String md5 = MD5Utils.md5(user.getUpassword());
        user.setUpassword(md5);

        //3.调用用户的业务逻辑进行注册
        try {
            userService.registerUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("registerMsg", "注册失败！");

            return "register";
        }

        //4.响应
        return "registerSuccess";
    }

    /**
     * 激活
     */
    @RequestMapping(value = "/active")
    public ModelAndView active(String c, ModelAndView modelAndView) {
        //1.获取激活码
        //已经转成base64
        //base64翻转
        String code = Base64Utils.decode(c);
        //2.调用激活的业务逻辑
        int i = userService.activeUser(code);

        //3.响应(激活失败（code没有找到） 已经激活 激活成功)
        if (i == Constants.ACTIVE_FAIL) {
            modelAndView.addObject("msg", "未激活成功！");
        } else if (i == Constants.ACTIVE_SUCCESS) {
            modelAndView.addObject("msg", "激活成功，请登录！");
        } else {
            modelAndView.addObject("msg", "已经激活");
        }

        modelAndView.setViewName("message");
        return modelAndView;
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @ResponseBody
    public String check(String username) {

        if (username == null) {
            return Constants.HAS_USER; //不能注册
        }
        //1.调用业务逻辑判断用户名是否存在
        boolean b = userService.checkedUser(username);

        //2.响应字符串  1 存在  0 不存在
        if (b) {
            //用户存在
            return Constants.HAS_USER;
        }
        return Constants.NOT_HAS_USER;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password,
                              @RequestParam("codes") String code, @RequestParam(value = "auto",required = false,defaultValue = "false") boolean auto, HttpServletResponse response,
                              ModelAndView modelAndView, Model model) {

        //1.正确的验证码
        String codestr = (String) model.getAttribute("code");

        //2.判断验证码是否正确
        if (code == null || !code.equalsIgnoreCase(codestr)) {
            modelAndView.addObject("msg", "验证码错误");
            modelAndView.setViewName("login");
            return modelAndView;
        }
        //3.调用业务逻辑判断账号密码
        User user = userService.login(username, password);

        //4.响应
        //user 等于null证明账号或者密码错误
        //user 不为null 但是user的状态是未激活状态

        if (user == null) {
            modelAndView.addObject("msg", "账号或者密码错误");
            modelAndView.setViewName("login");
            return modelAndView;
        }

        if (user.getUstatus().equals(Integer.valueOf(Constants.USER_NOT_ACTIVE))) {
            modelAndView.addObject("msg", "账号未激活！");
            modelAndView.setViewName("login");
            return modelAndView;
        }

        if(user.getUrole() == Constants.ROLE_ADMIN){ //如果用户为管理员的话
            model.addAttribute("admin",user);

            modelAndView.setViewName("/admin/admin");
            return modelAndView;
        }else {
            model.addAttribute("loginUser", user);
        }
        //autoUser
        //判断是否勾选自动登录
        if (!auto) {
            //没有勾选！
            //将本地浏览器的存储的cookie'清空'
            Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        } else {
            //自定登录数据库存储 2周
            String content = username + Constants.FLAG + password;
            content = Base64Utils.encode(content);
            Cookie cookie = new Cookie(Constants.AUTO_NAME, content);
            cookie.setPath("/");
            cookie.setMaxAge(14 * 24 * 60 * 60);
            response.addCookie(cookie);
        }
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 注销登录！清空数据！跳转到登录页面
     *
     * @param modelAndView
     * @param response
     * @return
     */
    @RequestMapping(value = "/logOut")
    public ModelAndView logOut(ModelAndView modelAndView, HttpServletResponse response, HttpSession session) {
        //1.清空session中的用户数据
        session.removeAttribute("loginUser");
        //2.清空和覆盖cookie存储的自动登录信息
        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //3.转发到登录页面
        modelAndView.addObject("msg", "注销登录成功！");
        modelAndView.setViewName("login");
        return modelAndView;
    }
}
